package 笔试.小米;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 2
// 1 8 5
// 4 6 3
// 0 2 0
// 1 3 5
// 4 6 8
// 2 7 0
public class 填充有效数独可能 {
    public static int ans = 0;
    public static int[][] matrix;
    public static boolean[] used;
    public static ArrayList<int[]> queue;
    public static List<Integer> list;
    public static int[][] dir = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while (T-- > 0) {
            init();
            solve(sc);
        }
    }

    private static void init() {
        ans = 0;
        matrix = new int[3][3];
        queue = new ArrayList<>();
        used = new boolean[10];
        list = new ArrayList<>();
    }

    private static void solve(Scanner sc) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = sc.nextInt();
                if (matrix[i][j] != 0) {
                    used[matrix[i][j]] = true;
                    if (i > 0 && matrix[i][j] > 0 && matrix[i - 1][j] > 0 && Math.abs(matrix[i][j] - matrix[i - 1][j]) == 1) {
                        System.out.println(0);
                        return;
                    }
                    if (j > 0 && matrix[i][j - 1] > 0 && matrix[i][j] > 0 && Math.abs(matrix[i][j - 1] - matrix[i][j]) == 1) {
                        System.out.println(0);
                        return;
                    }
                } else {
                    queue.add(new int[]{i, j});
                }
            }
        }
        for (int i = 1; i <= 9; i++) {
            if (!used[i]) {
                list.add(i);
            }
        }
        if (queue.size() != list.size()) {
            System.out.println(0);
            return;
        }
        int index = 0;
        dfs(index);
        System.out.println(ans);
    }

    private static void dfs(int index) {
        if (queue.size() == index) {
            if (list.isEmpty()) {
                ans++;
            }
            return;
        }
        int[] poll = queue.get(index);
        int x = poll[0];
        int y = poll[1];
        for (int i = 0; i < list.size(); i++) {
            Integer num = list.get(i);
            matrix[x][y] = num;
            list.remove(num);
            boolean flag = true;
            for (int j = 0; j < 4; j++) {
                int tx = x + dir[j][0];
                int ty = y + dir[j][1];
                if (checkValid(tx, ty) && Math.abs(num - matrix[tx][ty]) == 1) {
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                matrix[x][y] = 0;
                continue;
            }
            dfs(index + 1);
            list.add(i, num);
        }
    }

    public static boolean checkValid(int x, int y) {
        return x >= 0 && x < 3 && y >= 0 && y < 3;
    }
}